<?php
namespace app\home\controller;
use think\Db;
use think\Session;
class Order extends \think\Controller
{
    public function add(){
        $user_id = Session::get('id');
        if (!$user_id) {
            $this->redirect('user/login');
        }
        $all = input('post.');
        if($all){
//            dump($all);exit;
            $order_amount = $all['order_amount'];
            $goods_id = $all['goods_id'];
            $c_goods_number = $all['c_goods_number'];
            $goods_number = $all['goods_number'];
            
            db()->startTrans();  // 开启事务
            $flag = true;
            for($i=0;$i<count($goods_id);$i++){
                $number = $goods_number[$i] - $c_goods_number[$i];
                if($number < 0){
                    db()->rollback();
                    $this->error('商品数量不足!','flow/flowList');  
                }
               $info = Db::name('goods')->where('goods_id',$goods_id[$i])->update(['goods_number'=>$number]);
               if(!$info){
                   $flag = false;
               }
            }
            if($flag){
                //提交订单
                $data['order_amount'] =$order_amount;
                $data['order_sn'] = date('YmdHis',time()).rand(1000,9999);
                $data['order_create_time'] = date('Y-m-d H:i:s');
                $data['order_u_id'] = $user_id; 
                $id = Db::name('order')->insertGetId($data);
                if($id){
                    //更新购物车
                  $info = Db::name('cat')->where('c_user_id',$user_id)->where('c_status',0)->update(['c_status'=>1,'c_order_id'=>$id]);
                  if($info){
                      db()->commit();
                     $this->success('订单提交成功','flow/tijiao');
                  }
                }
            } 
              db()->rollback();
        }
            $this->error('订单提交失败','flow/flowList');
    }
    
   public function orderList(){
       $user_id = Session::get('id');
        if (!$user_id) {
            $this->redirect('user/login');
        }
        $data = Db::name('order')->where('order_u_id',$user_id)->where('order_status','in',[0,1,2])->select();
        $this->assign('data',$data);
        return	$this->fetch();
        
    }  
    
    public function detail(){
        $user_id = Session::get('id');
        if (!$user_id) {
            $this->redirect('user/login');
        }
        $id = input('param.order_id');
        $allprice = input('param.allprice');
        $data = Db::name('cat')->where('c_order_id',$id)->where('c_user_id',$user_id)->select();
        if($data){
        $this->assign('data',$data);        
        $this->assign('allprice',$allprice);
        }else{
            $this->error('没有权限访问','order/orderList');
        }

        return $this->fetch();
    }
    
}
